package com.example.demolib.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;


@Slf4j
@Component
//  创建拦截器类
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求的URI
        String uri = request.getRequestURI();
        log.info("preHandle: url = {}", uri);

        // 放行验证码和登录接口
        if (uri.contains("/book/captcha") || uri.contains("/book/login")) {
            return true;
        }

        // 检查session中是否有登录标记
        HttpSession session = request.getSession();
        Object loginFlag = session.getAttribute("loginUser");

        if (loginFlag == null) {
            // 未登录，返回401状态码
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("{\"code\":401,\"message\":\"nologin\"}");
            return false;
        }

        return true; // 已登录，放行
    }
}
